import os


def get_filenames(directory) -> list:
    res = []
    try:
        # 获取指定目录下的所有文件和文件夹名称
        entries = os.listdir(directory)
        for entry in entries:
            res.append(entry)
    except FileNotFoundError:
        print(f"指定的目录 {directory} 不存在。")
    return res


def get_filepaths(directory) -> list:
    all = []
    for root, dirs, files in os.walk(directory):
        paths = [os.path.join(root, f) for f in files]
        all = all + paths
    return all


def get_file_info(folder_path):
    file_info = []
    try:
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                file_absolute_path = os.path.join(root, file)
                file_info.append({
                    "name": file,
                    "path": file_absolute_path
                })
        return file_info
    except FileNotFoundError:
        print(f"错误：指定的文件夹 {folder_path} 未找到。")
        return []
    except Exception as e:
        print(f"发生未知错误: {e}")
        return []


def mkdir(file_path):
    # 获取文件的上级目录
    dir_path = os.path.dirname(file_path)
    # 检查目录是否存在
    if not os.path.exists(dir_path):
        try:
            # 递归创建目录
            os.makedirs(dir_path)
            print(f"成功创建目录: {dir_path}")
        except FileExistsError:
            # 在多线程或多进程环境下，可能出现目录已被其他进程创建的情况
            pass
        except PermissionError:
            print(f"没有权限创建目录: {dir_path}")
        except Exception as e:
            print(f"创建目录时出现错误: {e}")
    return dir_path


'''
只传前面两个参数，默认将该目录所有文件合并
如果传了files，则根据files里的文件合并
'''


def merge_file(source_dir, output_file, condition=None):
    output_file = os.path.join(source_dir, output_file)
    files = get_file_info(source_dir)
    try:
        with open(output_file, 'w', encoding='utf-8') as out_file:
            # 遍历目录下的所有文件
            for file in files:
                file_path = file['path']
                if (condition is not None) & (~condition(file['name'])):
                    continue
                print(file_path)
                try:
                    with open(file_path, 'r', encoding='utf-8') as in_file:
                        # 逐行读取文件内容并写入合并后的文件
                        for line in in_file:
                            out_file.write(line)
                        # 可以根据需要在每个文件内容后添加换行符
                        out_file.write('\n')
                except Exception as e:
                    print(f"读取文件 {file_path} 时出错: {e}")
        print(f"合并完成，结果保存到 {output_file}")
    except Exception as e:
        print(f"写入合并文件时出错: {e}")


def move(source_file, destination_directory):
    # 源文件路径 source_file
    # 目标目录路径 destination_directory

    # 构建目标文件的完整路径
    destination_file = os.path.join(destination_directory, os.path.basename(source_file))

    try:
        # 移动文件
        os.rename(source_file, destination_file)
        print(f"文件 {source_file} 已成功移动到 {destination_file}")
    except FileNotFoundError:
        print(f"源文件 {source_file} 未找到。")
    except PermissionError:
        print("没有足够的权限来移动文件。")
    except OSError:
        print("源和目标可能位于不同的文件系统，无法使用 os.rename() 移动。")
    except Exception as e:
        print(f"移动文件时出现错误: {e}")


def compare_df(df1, df2):
    # 对数据进行排序
    df1_sorted = df1.sort_values(by=list(df1.columns)).reset_index(drop=True)
    df2_sorted = df2.sort_values(by=list(df2.columns)).reset_index(drop=True)

    # 检查行数和列数是否相同
    if df1_sorted.shape != df2_sorted.shape:
        return False

    # 检查列名是否相同
    if list(df1_sorted.columns) != list(df2_sorted.columns):
        return False

    # 逐行逐列比较单元格值
    return df1_sorted.equals(df2_sorted)


def find_latest_file_with_keyword(directory, keyword):
    # 存储符合条件的文件及其修改时间
    files = []
    # 遍历指定目录及其子目录
    for root, _, filenames in os.walk(directory):
        for filename in filenames:
            # 检查文件名是否包含关键字
            if keyword in filename:
                file_path = os.path.join(root, filename)
                # 获取文件的修改时间
                modification_time = os.path.getmtime(file_path)
                files.append((file_path, modification_time))

    # 如果没有找到符合条件的文件，返回 None
    if not files:
        return None

    # 按修改时间降序排序
    files.sort(key=lambda x: x[1], reverse=True)
    # 返回最新的文件路径
    return files[0][0]


def find_large_files(directory, min_size_mb=200):
    """
    查找指定目录下所有大小超过 min_size_mb MB 的文件

    :param directory: 要搜索的目录路径
    :param min_size_mb: 最小文件大小（MB），默认 200MB
    :return: 返回符合条件的文件列表，每个元素是 (文件路径, 文件大小MB)
    """
    large_files = []
    min_size_bytes = min_size_mb * 1024 * 1024  # 转换为字节

    for root, _, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                file_size = os.path.getsize(file_path)
                if file_size > min_size_bytes:
                    file_size_mb = file_size / (1024 * 1024)
                    large_files.append((file_path, round(file_size_mb, 2)))
            except (OSError, PermissionError) as e:
                print(f"无法访问文件 {file_path}: {e}")

    return large_files


def merge_xlsx_files(directory, output_file="output.xlsx"):
    """
    读取目录下所有xlsx文件，合并为一个DataFrame后一次性写入output_file。
    :param directory: 目录路径
    :param output_file: 输出文件名
    """
    import pandas as pd
    import os
    all_files = [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith('.xlsx')]
    if not all_files:
        print("未找到可合并的xlsx文件。")
        return
    df_list = []
    for file in all_files:
        try:
            df = pd.read_excel(file, dtype=str)
            df_list.append(df)
            print(file)
        except Exception as e:
            print(f"读取文件 {file} 时出错: {e}")
    if df_list:
        merged_df = pd.concat(df_list, ignore_index=True)
        output_path = os.path.join(directory, output_file)
        merged_df.to_excel(output_path, index=False)
        print(f"合并完成，结果保存到 {output_path}")
    else:
        print("没有可合并的数据。")


if __name__ == '__main__':
    merge_xlsx_files(r"D:\Download\WeChat Files\wxid_kdchbeq2xllp22\FileStorage\File\2025-07\新建文件夹")
